import mongoose, { Schema, Document, Model } from 'mongoose';
import { IPermissionDocument } from './permission';

/**
 * 组织权限关联接口
 * 用于管理组织（团队/部门/小组）与权限之间的关联关系
 */
export interface IOrganizationPermission {
  /** 组织ID */
  organizationId: mongoose.Types.ObjectId;
  /** 组织类型：team-团队, department-部门, group-小组 */
  organizationType: 'team' | 'department' | 'group';
  /** 权限ID */
  permissionId: mongoose.Types.ObjectId;
  /** 所属系统ID（可选，支持多系统权限管理） */
  systemId?: mongoose.Types.ObjectId;
  /** 分配者ID */
  assignedBy: mongoose.Types.ObjectId;
  /** 分配时间 */
  assignedAt: Date;
  /** 过期时间（可选） */
  expiresAt?: Date;
  /** 状态：1-启用，0-禁用 */
  status: number;
  /** 是否继承给下级组织：true-继承，false-不继承 */
  inherited: boolean;
  /** 权限来源：direct-直接分配，inherited-继承获得 */
  source: 'direct' | 'inherited';
  /** 父级组织权限ID（继承权限时使用） */
  parentPermissionId?: mongoose.Types.ObjectId;
  /** 创建时间 */
  createdAt: Date;
  /** 更新时间 */
  updatedAt: Date;
}

/**
 * 组织权限关联文档接口
 */
export interface IOrganizationPermissionDocument extends IOrganizationPermission, Document {
  /**
   * 转换为JSON格式
   * @returns 格式化的组织权限信息
   */
  toJSON(): any;

  /**
   * 检查权限是否已过期
   * @returns 是否过期
   */
  isExpired(): boolean;

  /**
   * 检查是否可以删除
   * @returns 是否可删除
   */
  canBeDeleted(): boolean;

  /**
   * 获取详细信息（包含关联数据）
   * @returns 包含组织、权限、分配者信息的详细数据
   */
  getDetailInfo(): Promise<any>;

  /**
   * 检查是否为继承权限
   * @returns 是否为继承权限
   */
  isInherited(): boolean;

  /**
   * 获取权限继承路径
   * @returns 权限继承路径数组
   */
  getInheritancePath(): Promise<IOrganizationPermissionDocument[]>;
}

/**
 * 组织权限关联模型接口
 */
export interface IOrganizationPermissionModel extends Model<IOrganizationPermissionDocument> {
  /**
   * 根据组织ID查询权限
   * @param organizationId 组织ID
   * @param organizationType 组织类型
   * @param systemId 系统ID（可选）
   * @returns 组织权限列表
   */
  findByOrganizationId(
    organizationId: mongoose.Types.ObjectId,
    organizationType?: 'team' | 'department' | 'group',
    systemId?: mongoose.Types.ObjectId
  ): Promise<IOrganizationPermissionDocument[]>;

  /**
   * 根据权限ID查询组织
   * @param permissionId 权限ID
   * @param systemId 系统ID（可选）
   * @returns 拥有该权限的组织列表
   */
  findByPermissionId(
    permissionId: mongoose.Types.ObjectId,
    systemId?: mongoose.Types.ObjectId
  ): Promise<IOrganizationPermissionDocument[]>;

  /**
   * 根据系统ID查询组织权限
   * @param systemId 系统ID
   * @returns 系统内组织权限列表
   */
  findBySystemId(systemId: mongoose.Types.ObjectId): Promise<IOrganizationPermissionDocument[]>;

  /**
   * 检查组织是否拥有特定权限
   * @param organizationId 组织ID
   * @param organizationType 组织类型
   * @param permissionId 权限ID
   * @param systemId 系统ID（可选）
   * @returns 是否拥有权限
   */
  hasPermission(
    organizationId: mongoose.Types.ObjectId,
    organizationType: 'team' | 'department' | 'group',
    permissionId: mongoose.Types.ObjectId,
    systemId?: mongoose.Types.ObjectId
  ): Promise<boolean>;

  /**
   * 批量分配组织权限
   * @param organizationId 组织ID
   * @param organizationType 组织类型
   * @param permissionIds 权限ID数组
   * @param assignedBy 分配者ID
   * @param systemId 系统ID（可选）
   * @param options 分配选项
   * @returns 分配结果
   */
  batchAssign(
    organizationId: mongoose.Types.ObjectId,
    organizationType: 'team' | 'department' | 'group',
    permissionIds: mongoose.Types.ObjectId[],
    assignedBy: mongoose.Types.ObjectId,
    systemId?: mongoose.Types.ObjectId,
    options?: {
      expiresAt?: Date;
      inherited?: boolean;
      source?: 'direct' | 'inherited';
      parentPermissionId?: mongoose.Types.ObjectId;
    }
  ): Promise<{
    success: IOrganizationPermissionDocument[];
    failed: { permissionId: mongoose.Types.ObjectId; error: string }[];
  }>;

  /**
   * 批量撤销组织权限
   * @param organizationId 组织ID
   * @param organizationType 组织类型
   * @param permissionIds 权限ID数组（可选，不传则撤销所有权限）
   * @param systemId 系统ID（可选）
   * @returns 撤销数量
   */
  batchRevoke(
    organizationId: mongoose.Types.ObjectId,
    organizationType: 'team' | 'department' | 'group',
    permissionIds?: mongoose.Types.ObjectId[],
    systemId?: mongoose.Types.ObjectId
  ): Promise<number>;

  /**
   * 获取组织在特定系统中的权限
   * @param organizationId 组织ID
   * @param organizationType 组织类型
   * @param systemId 系统ID
   * @param includeInherited 是否包含继承权限
   * @returns 组织权限列表
   */
  getOrganizationPermissionsInSystem(
    organizationId: mongoose.Types.ObjectId,
    organizationType: 'team' | 'department' | 'group',
    systemId: mongoose.Types.ObjectId,
    includeInherited?: boolean
  ): Promise<IOrganizationPermissionDocument[]>;

  /**
   * 获取即将过期的组织权限
   * @param days 提前天数
   * @param systemId 系统ID（可选）
   * @returns 即将过期的权限列表
   */
  getExpiringPermissions(
    days: number,
    systemId?: mongoose.Types.ObjectId
  ): Promise<IOrganizationPermissionDocument[]>;

  /**
   * 清理已过期的组织权限
   * @param systemId 系统ID（可选）
   * @returns 清理数量
   */
  cleanupExpiredPermissions(systemId?: mongoose.Types.ObjectId): Promise<number>;

  /**
   * 同步组织权限（用于权限变更时的同步）
   * @param organizationId 组织ID
   * @param organizationType 组织类型
   * @param permissionIds 新的权限ID数组
   * @param assignedBy 分配者ID
   * @param systemId 系统ID（可选）
   * @returns 同步结果
   */
  syncOrganizationPermissions(
    organizationId: mongoose.Types.ObjectId,
    organizationType: 'team' | 'department' | 'group',
    permissionIds: mongoose.Types.ObjectId[],
    assignedBy: mongoose.Types.ObjectId,
    systemId?: mongoose.Types.ObjectId
  ): Promise<{
    added: IOrganizationPermissionDocument[];
    removed: number;
  }>;

  /**
   * 继承上级组织权限
   * @param childOrganizationId 子组织ID
   * @param childOrganizationType 子组织类型
   * @param parentOrganizationId 父组织ID
   * @param parentOrganizationType 父组织类型
   * @param assignedBy 分配者ID
   * @param systemId 系统ID（可选）
   * @returns 继承的权限列表
   */
  inheritFromParent(
    childOrganizationId: mongoose.Types.ObjectId,
    childOrganizationType: 'team' | 'department' | 'group',
    parentOrganizationId: mongoose.Types.ObjectId,
    parentOrganizationType: 'team' | 'department' | 'group',
    assignedBy: mongoose.Types.ObjectId,
    systemId?: mongoose.Types.ObjectId
  ): Promise<IOrganizationPermissionDocument[]>;

  /**
   * 获取权限被分配给的组织数量
   * @param permissionId 权限ID
   * @param systemId 系统ID（可选）
   * @param organizationType 组织类型（可选）
   * @returns 组织数量
   */
  getPermissionOrganizationCount(
    permissionId: mongoose.Types.ObjectId,
    systemId?: mongoose.Types.ObjectId,
    organizationType?: 'team' | 'department' | 'group'
  ): Promise<number>;

  /**
   * 获取组织拥有的权限数量
   * @param organizationId 组织ID
   * @param organizationType 组织类型
   * @param systemId 系统ID（可选）
   * @param includeInherited 是否包含继承权限
   * @returns 权限数量
   */
  getOrganizationPermissionCount(
    organizationId: mongoose.Types.ObjectId,
    organizationType: 'team' | 'department' | 'group',
    systemId?: mongoose.Types.ObjectId,
    includeInherited?: boolean
  ): Promise<number>;
}

/**
 * 组织权限关联Schema
 */
const OrganizationPermissionSchema = new Schema<IOrganizationPermissionDocument>({
  // 组织ID
  organizationId: {
    type: Schema.Types.ObjectId,
    required: [true, '组织ID不能为空'],
    index: true
  },
  // 组织类型
  organizationType: {
    type: String,
    required: [true, '组织类型不能为空'],
    enum: {
      values: ['team', 'department', 'group'],
      message: '组织类型必须是team、department或group之一'
    },
    index: true
  },
  // 权限ID
  permissionId: {
    type: Schema.Types.ObjectId,
    ref: 'Permission',
    required: [true, '权限ID不能为空'],
    index: true
  },
  // 系统ID
  systemId: {
    type: Schema.Types.ObjectId,
    ref: 'System',
    index: true
  },
  // 分配者ID
  assignedBy: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: [true, '分配者ID不能为空']
  },
  // 分配时间
  assignedAt: {
    type: Date,
    default: Date.now
  },
  // 过期时间
  expiresAt: {
    type: Date,
    index: { sparse: true }
  },
  // 状态
  status: {
    type: Number,
    required: [true, '状态不能为空'],
    enum: {
      values: [0, 1],
      message: '状态必须是0（禁用）或1（启用）'
    },
    default: 1,
    index: true
  },
  // 是否继承给下级组织
  inherited: {
    type: Boolean,
    default: true,
    index: true
  },
  // 权限来源
  source: {
    type: String,
    required: [true, '权限来源不能为空'],
    enum: {
      values: ['direct', 'inherited'],
      message: '权限来源必须是direct或inherited之一'
    },
    default: 'direct',
    index: true
  },
  // 父级组织权限ID
  parentPermissionId: {
    type: Schema.Types.ObjectId,
    ref: 'OrganizationPermission',
    index: true
  }
}, {
  timestamps: true,
  versionKey: false
});

// 复合索引
OrganizationPermissionSchema.index(
  { organizationId: 1, organizationType: 1, permissionId: 1, systemId: 1 },
  { unique: true, name: 'unique_org_permission' }
);
OrganizationPermissionSchema.index(
  { organizationId: 1, organizationType: 1, systemId: 1, status: 1 },
  { name: 'org_system_status' }
);
OrganizationPermissionSchema.index(
  { permissionId: 1, systemId: 1, status: 1 },
  { name: 'permission_system_status' }
);
OrganizationPermissionSchema.index(
  { expiresAt: 1, status: 1 },
  { sparse: true, name: 'expires_status' }
);
OrganizationPermissionSchema.index(
  { source: 1, inherited: 1, status: 1 },
  { name: 'source_inherited_status' }
);

// TTL索引：自动清理过期的权限关联
OrganizationPermissionSchema.index(
  { expiresAt: 1 },
  { expireAfterSeconds: 0, sparse: true, background: true }
);

// Pre-save中间件：设置分配时间
OrganizationPermissionSchema.pre('save', function(next) {
  if (this.isNew && !this.assignedAt) {
    this.assignedAt = new Date();
  }
  next();
});

// 实例方法：转换为JSON
OrganizationPermissionSchema.methods.toJSON = function() {
  const obj = this.toObject();
  delete obj.__v;
  return obj;
};

// 实例方法：检查是否过期
OrganizationPermissionSchema.methods.isExpired = function(): boolean {
  if (!this.expiresAt) return false;
  return new Date() > this.expiresAt;
};

// 实例方法：检查是否可删除
OrganizationPermissionSchema.methods.canBeDeleted = function(): boolean {
  return this.status === 0 || this.isExpired();
};

// 实例方法：获取详细信息
OrganizationPermissionSchema.methods.getDetailInfo = async function() {
  await this.populate([
    { path: 'permissionId', select: 'name code description type' },
    { path: 'assignedBy', select: 'username realName' }
  ]);
  return this.toJSON();
};

// 实例方法：检查是否为继承权限
OrganizationPermissionSchema.methods.isInherited = function(): boolean {
  return this.source === 'inherited';
};

// 实例方法：获取权限继承路径
OrganizationPermissionSchema.methods.getInheritancePath = async function(): Promise<IOrganizationPermissionDocument[]> {
  const path: IOrganizationPermissionDocument[] = [this as any];
  let current: any = this;
  
  while (current.parentPermissionId) {
    current = await (this.constructor as IOrganizationPermissionModel)
      .findById(current.parentPermissionId);
    if (current) {
      path.unshift(current as any);
    } else {
      break;
    }
  }
  
  return path;
};

// 静态方法：根据组织ID查询权限
OrganizationPermissionSchema.statics.findByOrganizationId = async function(
  organizationId: mongoose.Types.ObjectId,
  organizationType?: 'team' | 'department' | 'group',
  systemId?: mongoose.Types.ObjectId
): Promise<IOrganizationPermissionDocument[]> {
  const query: any = {
    organizationId,
    status: 1
  };
  
  if (organizationType) {
    query.organizationType = organizationType;
  }
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  return (this as IOrganizationPermissionModel).find(query)
    .populate('permissionId', 'name code description type')
    .sort({ assignedAt: -1 });
};

// 静态方法：根据权限ID查询组织
OrganizationPermissionSchema.statics.findByPermissionId = async function(
  permissionId: mongoose.Types.ObjectId,
  systemId?: mongoose.Types.ObjectId
): Promise<IOrganizationPermissionDocument[]> {
  const query: any = {
    permissionId,
    status: 1
  };
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  return (this as IOrganizationPermissionModel).find(query)
    .populate('permissionId', 'name code description type')
    .sort({ assignedAt: -1 });
};

// 静态方法：根据系统ID查询组织权限
OrganizationPermissionSchema.statics.findBySystemId = async function(
  systemId: mongoose.Types.ObjectId
): Promise<IOrganizationPermissionDocument[]> {
  return (this as IOrganizationPermissionModel).find({
    systemId,
    status: 1
  })
  .populate('permissionId', 'name code description type')
  .populate('assignedBy', 'username realName')
  .sort({ assignedAt: -1 });
};

// 静态方法：检查组织是否拥有特定权限
OrganizationPermissionSchema.statics.hasPermission = async function(
  organizationId: mongoose.Types.ObjectId,
  organizationType: 'team' | 'department' | 'group',
  permissionId: mongoose.Types.ObjectId,
  systemId?: mongoose.Types.ObjectId
): Promise<boolean> {
  const query: any = {
    organizationId,
    organizationType,
    permissionId,
    status: 1,
    $or: [
      { expiresAt: { $exists: false } },
      { expiresAt: { $gt: new Date() } }
    ]
  };
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  const count = await (this as IOrganizationPermissionModel).countDocuments(query);
  return count > 0;
};

// 静态方法：批量分配组织权限
OrganizationPermissionSchema.statics.batchAssign = async function(
  organizationId: mongoose.Types.ObjectId,
  organizationType: 'team' | 'department' | 'group',
  permissionIds: mongoose.Types.ObjectId[],
  assignedBy: mongoose.Types.ObjectId,
  systemId?: mongoose.Types.ObjectId,
  options?: {
    expiresAt?: Date;
    inherited?: boolean;
    source?: 'direct' | 'inherited';
    parentPermissionId?: mongoose.Types.ObjectId;
  }
): Promise<{
  success: IOrganizationPermissionDocument[];
  failed: { permissionId: mongoose.Types.ObjectId; error: string }[];
}> {
  const success: IOrganizationPermissionDocument[] = [];
  const failed: { permissionId: mongoose.Types.ObjectId; error: string }[] = [];
  
  for (const permissionId of permissionIds) {
    try {
      // 检查是否已存在
      const existing = await (this as IOrganizationPermissionModel).findOne({
        organizationId,
        organizationType,
        permissionId,
        systemId
      });
      
      if (existing) {
        if (existing.status === 0) {
          // 重新启用
          existing.status = 1;
          existing.assignedBy = assignedBy;
          existing.assignedAt = new Date();
          if (options?.expiresAt) existing.expiresAt = options.expiresAt;
          await existing.save();
          success.push(existing);
        } else {
          failed.push({ permissionId, error: '权限已存在' });
        }
      } else {
        // 创建新的权限关联
        const orgPermission = new (this as IOrganizationPermissionModel)({
          organizationId,
          organizationType,
          permissionId,
          systemId,
          assignedBy,
          status: 1,
          inherited: options?.inherited ?? true,
          source: options?.source ?? 'direct',
          parentPermissionId: options?.parentPermissionId,
          expiresAt: options?.expiresAt
        });
        
        await orgPermission.save();
        success.push(orgPermission);
      }
    } catch (error) {
      failed.push({ 
        permissionId, 
        error: error instanceof Error ? error.message : '未知错误' 
      });
    }
  }
  
  return { success, failed };
};

// 静态方法：批量撤销组织权限
OrganizationPermissionSchema.statics.batchRevoke = async function(
  organizationId: mongoose.Types.ObjectId,
  organizationType: 'team' | 'department' | 'group',
  permissionIds?: mongoose.Types.ObjectId[],
  systemId?: mongoose.Types.ObjectId
): Promise<number> {
  const query: any = {
    organizationId,
    organizationType
  };
  
  if (permissionIds && permissionIds.length > 0) {
    query.permissionId = { $in: permissionIds };
  }
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  const result = await (this as IOrganizationPermissionModel).deleteMany(query);
  return result.deletedCount || 0;
};

// 静态方法：获取组织在特定系统中的权限
OrganizationPermissionSchema.statics.getOrganizationPermissionsInSystem = async function(
  organizationId: mongoose.Types.ObjectId,
  organizationType: 'team' | 'department' | 'group',
  systemId: mongoose.Types.ObjectId,
  includeInherited: boolean = true
): Promise<IOrganizationPermissionDocument[]> {
  const query: any = {
    organizationId,
    organizationType,
    systemId,
    status: 1,
    $or: [
      { expiresAt: { $exists: false } },
      { expiresAt: { $gt: new Date() } }
    ]
  };
  
  if (!includeInherited) {
    query.source = 'direct';
  }
  
  return (this as IOrganizationPermissionModel).find(query)
    .populate('permissionId', 'name code description type')
    .sort({ assignedAt: -1 });
};

// 静态方法：获取即将过期的组织权限
OrganizationPermissionSchema.statics.getExpiringPermissions = async function(
  days: number,
  systemId?: mongoose.Types.ObjectId
): Promise<IOrganizationPermissionDocument[]> {
  const expiryDate = new Date();
  expiryDate.setDate(expiryDate.getDate() + days);
  
  const query: any = {
    status: 1,
    expiresAt: {
      $exists: true,
      $lte: expiryDate,
      $gt: new Date()
    }
  };
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  return (this as IOrganizationPermissionModel).find(query)
    .populate('permissionId', 'name code description')
    .populate('assignedBy', 'username realName')
    .sort({ expiresAt: 1 });
};

// 静态方法：清理已过期的组织权限
OrganizationPermissionSchema.statics.cleanupExpiredPermissions = async function(
  systemId?: mongoose.Types.ObjectId
): Promise<number> {
  const query: any = {
    expiresAt: {
      $exists: true,
      $lt: new Date()
    }
  };
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  const result = await (this as IOrganizationPermissionModel).deleteMany(query);
  return result.deletedCount || 0;
};

// 静态方法：同步组织权限
OrganizationPermissionSchema.statics.syncOrganizationPermissions = async function(
  organizationId: mongoose.Types.ObjectId,
  organizationType: 'team' | 'department' | 'group',
  permissionIds: mongoose.Types.ObjectId[],
  assignedBy: mongoose.Types.ObjectId,
  systemId?: mongoose.Types.ObjectId
): Promise<{
  added: IOrganizationPermissionDocument[];
  removed: number;
}> {
  // 获取当前权限
  const currentPermissions = await (this as IOrganizationPermissionModel).findByOrganizationId(
    organizationId,
    organizationType,
    systemId
  );
  
  const currentPermissionIds = currentPermissions.map((op: IOrganizationPermissionDocument) => op.permissionId?.toString()).filter(Boolean);
  const newPermissionIds = permissionIds.map(id => id.toString());
  
  // 计算需要添加和删除的权限
  const toAdd = permissionIds.filter(id => !currentPermissionIds.includes(id.toString()));
  const toRemove = currentPermissions
    .filter((op: IOrganizationPermissionDocument) => op.permissionId && !newPermissionIds.includes(op.permissionId.toString()))
    .map((op: IOrganizationPermissionDocument) => op.permissionId);
  
  // 添加新权限
  const addResult = await (this as IOrganizationPermissionModel).batchAssign(
    organizationId,
    organizationType,
    toAdd,
    assignedBy,
    systemId
  );
  
  // 删除旧权限
  const removeCount = await (this as IOrganizationPermissionModel).batchRevoke(
    organizationId,
    organizationType,
    toRemove,
    systemId
  );
  
  return {
    added: addResult.success,
    removed: removeCount
  };
};

// 静态方法：继承上级组织权限
OrganizationPermissionSchema.statics.inheritFromParent = async function(
  childOrganizationId: mongoose.Types.ObjectId,
  childOrganizationType: 'team' | 'department' | 'group',
  parentOrganizationId: mongoose.Types.ObjectId,
  parentOrganizationType: 'team' | 'department' | 'group',
  assignedBy: mongoose.Types.ObjectId,
  systemId?: mongoose.Types.ObjectId
): Promise<IOrganizationPermissionDocument[]> {
  // 获取父组织的可继承权限
  const parentPermissions = await (this as IOrganizationPermissionModel).find({
    organizationId: parentOrganizationId,
    organizationType: parentOrganizationType,
    systemId,
    status: 1,
    inherited: true,
    $or: [
      { expiresAt: { $exists: false } },
      { expiresAt: { $gt: new Date() } }
    ]
  });
  
  const inheritedPermissions: IOrganizationPermissionDocument[] = [];
  
  for (const parentPermission of parentPermissions) {
    try {
      // 检查子组织是否已有该权限
      const existing = await (this as IOrganizationPermissionModel).findOne({
        organizationId: childOrganizationId,
        organizationType: childOrganizationType,
        permissionId: parentPermission.permissionId,
        systemId
      });
      
      if (!existing) {
        // 创建继承权限
        const inheritedPermission = new (this as IOrganizationPermissionModel)({
          organizationId: childOrganizationId,
          organizationType: childOrganizationType,
          permissionId: parentPermission.permissionId,
          systemId,
          assignedBy,
          status: 1,
          inherited: true,
          source: 'inherited',
          parentPermissionId: parentPermission._id,
          expiresAt: parentPermission.expiresAt
        });
        
        await inheritedPermission.save();
        inheritedPermissions.push(inheritedPermission);
      }
    } catch (error) {
      // 忽略重复权限错误，继续处理其他权限
      console.warn(`继承权限失败: ${error}`);
    }
  }
  
  return inheritedPermissions;
};

// 静态方法：获取权限被分配给的组织数量
OrganizationPermissionSchema.statics.getPermissionOrganizationCount = async function(
  permissionId: mongoose.Types.ObjectId,
  systemId?: mongoose.Types.ObjectId,
  organizationType?: 'team' | 'department' | 'group'
): Promise<number> {
  const query: any = {
    permissionId,
    status: 1,
    $or: [
      { expiresAt: { $exists: false } },
      { expiresAt: { $gt: new Date() } }
    ]
  };
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  if (organizationType) {
    query.organizationType = organizationType;
  }
  
  return (this as IOrganizationPermissionModel).countDocuments(query);
};

// 静态方法：获取组织拥有的权限数量
OrganizationPermissionSchema.statics.getOrganizationPermissionCount = async function(
  organizationId: mongoose.Types.ObjectId,
  organizationType: 'team' | 'department' | 'group',
  systemId?: mongoose.Types.ObjectId,
  includeInherited: boolean = true
): Promise<number> {
  const query: any = {
    organizationId,
    organizationType,
    status: 1,
    $or: [
      { expiresAt: { $exists: false } },
      { expiresAt: { $gt: new Date() } }
    ]
  };
  
  if (systemId) {
    query.systemId = systemId;
  }
  
  if (!includeInherited) {
    query.source = 'direct';
  }
  
  return (this as IOrganizationPermissionModel).countDocuments(query);
};

// 创建并导出模型
const OrganizationPermission = mongoose.model<IOrganizationPermissionDocument, IOrganizationPermissionModel>(
  'OrganizationPermission',
  OrganizationPermissionSchema
);

export default OrganizationPermission;
export { OrganizationPermissionSchema };